import { computed, watch, reactive, ref} from 'vue'
import { useRoute, useRouter } from 'vue-router'

//缓存路由页面组件名称数组
interface IncludeNames extends Array<string> {}

//路由path、页面名称字典
interface PathNameDic {
  [path: string]: string
}

//页面组件name、路由path字典
interface ComponentNamePathDic {
  [name: string]: string
}

//路由path、页面组件name 字典
interface PathComponentNameDic {
  [path: string]: string
}

//菜单数据
interface Menu {
  label: string,
  path?: string,
  children?: Array<Menu>
}
export interface MenuList extends Array<Menu> {}

const includeNames: IncludeNames = reactive([])
let pathNameDic: PathNameDic = reactive({})
const componentNamePathDic: ComponentNamePathDic = reactive({})
const pathComponentNameDic: PathComponentNameDic = reactive({})
const currentPath = ref('')

const translateMenuToDic = (arr: Array<Menu>, result: PathNameDic = {}): PathNameDic => {
  arr.forEach((item) => {
    if (item.children && item.children.length > 0) {
      translateMenuToDic(item.children, result)
    } else if (item.path) {
      result[item.path] = item.label
    }
  })
  return result
}

/**
 * 监听路由，并且返回当前缓存的路由组件名称数组
 * @param route 
 * @param router 
 */
export const useCacheViews = (menu: Array<Menu>) => {
  const route = useRoute()
  const router = useRouter()

  const routes: Array<any> = router.getRoutes()
  pathNameDic = translateMenuToDic(menu)

  watch(
    () => route.path,
    (value) => {
      currentPath.value = value
      for (const route of routes) {
        if (currentPath.value === route.path) {
          const componentName = route.components.default.name
          if (componentName) {
            if (!includeNames.includes(componentName)) {
              includeNames.push(componentName)
            }
            componentNamePathDic[componentName] = currentPath.value
            pathComponentNameDic[currentPath.value] = componentName
          }
          break
        }
      }
    },
    {
      immediate: true
    }
  )

  const tabsData = computed(() => {
    const arr: Array<Object> = []
    includeNames.forEach(name => {
      const path = componentNamePathDic[name]
      arr.push({
        path,
        componentName: name,
        pageName: pathNameDic[path],
        active: currentPath.value === path
      })
    });
    return arr
  })

  return {
    includeNames,
    tabsData,
    removeCacheView(path: string) {
      const index = includeNames.indexOf(pathComponentNameDic[path])
      if (index > -1) {
        includeNames.splice(index, 1)
      }
      if (path === route.path) {
        const firstCacheComponentName = includeNames[0]
        router.push(componentNamePathDic[firstCacheComponentName])
      }
    }
  }
}